import { EventMgr } from "../../core/module/event/EventMgr";
import { SocketMsgCallback, SocketReason, SocketRespWrap, SocketState } from "../../core/module/socket/BaseTypes";
import { ClientSocket } from "../../core/module/socket/ClientSocket";
import { MsgType, Protocol } from "../../proto/msg";
import { app } from "../app/App";
import { SceneEnum } from "../share/Enum";

export class NetMgr {
    private _server: ClientSocket = null
    private _event: EventMgr = null

    constructor() {
        this._server = new ClientSocket()
        this._event = new EventMgr()

        this._server.onCloseCallback = this._onClose.bind(this)
        this._server.onMsgCallback = this._onMsg.bind(this)
    }


    connect(ip: string, port: string, callback?) {
        this._server.connect(ip, port, callback)
    }

    close() {
        this._server.forceClose()
    }

    sendData(msgId: number, body: any = {}, callback?: SocketMsgCallback) {
        this._server.sendData(msgId, body, callback)
    }

    onPushMsg(obj: object, msgId: number, callback: SocketMsgCallback) {
        this._event.on(obj, msgId, callback)
    }

    offPushMsg(obj: object, msgId: number) {
        this._event.off(obj, msgId)
    }

    offAllPushMsg(obj: object) {
        this._event.offAll(obj)
    }

    private _onClose(reason: SocketReason) {
        if (reason == SocketReason.FORCE) return
        app.toast.showAlert('连接断开,请检查网络连接', () => app.scene.startScene(SceneEnum.Login))
    }

    private _onMsg(msgType: MsgType, resp: SocketRespWrap) {
        if (msgType == MsgType.PUSH) {
            if (resp.cmd == Protocol.PUSH_LOGIN_OTHER) {
                app.net.close()
                app.toast.showAlert('该账号在其他位置登录了', () => app.scene.startScene(SceneEnum.Login))
            }
            this._event.emit(resp.cmd, resp)
        }
    }
}